<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="querryParmas.keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="getInputChange"
        />
        <!-- 树形组件 -->
        <!-- @current-change=""回调函数，默认两个数据，1当前节点数据，2当前节点node对象 -->
        <el-tree
          ref="Employeetree"
          node-key="id"
          highlight-current
          :data="employeeList"
          :props="{label:'name'}"
          :expand-on-click-node="false"
          default-expand-all
          @current-change="selectNode"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button v-permission="addEmployee" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button v-permission="addEmployee" size="mini" @click="showExcelDialog=true">excel导入</el-button>
          <el-button size="mini" @click="outExcelClick">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="empList">
          <el-table-column prop="staffPhoto" label="头像" align="center" width="80">
            <template #default="{row}">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30" />
              <span v-else class="username">{{ row.username[0] }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" width="100" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template #default="{row}">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column label="操作" width="200px">
            <template #default="{row}">
              <el-button type="text" size="mini" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="mini" @click="roleClick(row.id)">角色</el-button>
              <el-popconfirm
                v-permission="delEmployee"
                title="这是一段内容确定删除吗？"
                @onConfirm="Delemp(row.id)"
              >
                <el-button slot="reference" type="text" size="mini">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!--
          分页
          total：总数   current-page：当前页码   page-size：每页多少条数  current-change点击页码时发生的变化
        -->
        <el-row type="flex" style="height: 60px" justify="end" align="middle">
          <el-pagination
            layout="total, prev, pager, next"
            :total="total"
            :current-page="querryParmas.page"
            :page-size="querryParmas.pagesize"
            @current-change="currentChange"
          />
        </el-row>
      </div>
    </div>
    <importExcel :show-excel-dialog.sync="showExcelDialog" @uploadExcel="getempList" />
    <el-dialog title="分配角色" :visible.sync="showRoleDialog" @close="close">
      <el-checkbox-group v-model="roleIds">
        <el-checkbox
          v-for="item in roleList"
          :key="item.id"
          :label="item.id"
        >{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <template #footer>
        <el-row type="flex" justify="center">
          <el-button type="primary" size="mini" @click="roleConfirmClick">确定</el-button>
          <el-button size="mini" @click="close">取消</el-button>
        </el-row>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listToTreeList } from '@/utils/index'
import { departmentDataAPI } from '@/api/department'
import { getEmployeeListAPI,
  outExcelListAPI,
  delEmployeeAPI,
  getEmployeeDataAPI,
  getEnableRoleListAPI,
  assignRoleAPI
} from '@/api/employee'
import Filesver from 'file-saver'
import importExcel from './components/import-excel.vue'
export default {
  name: 'Employee',
  components: {
    importExcel
  },
  data() {
    return {
      employeeList: [],
      querryParmas: {
        departmentID: null,
        page: 1,
        pagesize: 10,
        keyword: ''
      },
      total: 0,
      showExcelDialog: false,
      empList: [],
      // 控制分配角色的显示和隐藏
      showRoleDialog: false,
      // 复选框数据
      roleList: [],
      currentRoleId: null,
      // 双向绑定，记录用户选中的值
      roleIds: []
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    // 初始化加载数据
    async getEmployeeList() {
      this.employeeList = listToTreeList(await departmentDataAPI(), 0)
      this.querryParmas.departmentID = this.employeeList[0].id

      this.$nextTick(() => {
        this.$refs.Employeetree.setCurrentKey(this.employeeList[0].id)
      })
      this.getempList()
    },
    // 设置node节点（点击左树后获取对应ID，右表切换）
    selectNode(nodeData) {
      this.querryParmas.departmentID = nodeData.id
      this.querryParmas.page = 1
    },
    // 获取员工列表信息
    async getempList() {
      const { rows, total } = await getEmployeeListAPI(this.querryParmas)
      this.empList = rows
      this.total = total
    },
    // 点击页码时触发的事件
    currentChange(currentPage) {
      this.querryParmas.page = currentPage
      this.getempList()
    },
    // input事件发生变化
    getInputChange() {
      clearTimeout(this.time)
      this.time = setTimeout(() => {
        this.querryParmas.page = 1
        this.getempList()
      }, 300)
    },
    // 批量导出excel
    async outExcelClick() {
      const res = await outExcelListAPI()
      Filesver.saveAs(res, '员工人员名单.xlsx')
    },
    async Delemp(id) {
      await delEmployeeAPI(id)
      this.$message.success('删除成功')
      this.getempList()
      if (this.empList.length === 1 && this.querryParmas.page > 1) {
        this.querryParmas.page--
      }
    },
    async roleClick(id) {
      this.showRoleDialog = true
      this.currentRoleId = id
      this.roleList = await getEnableRoleListAPI()
      const { roleIds } = await getEmployeeDataAPI(id)
      this.roleIds = roleIds
    },
    close() {
      this.roleIds = []
      this.showRoleDialog = false
    },
    async roleConfirmClick() {
      await assignRoleAPI({ id: this.currentRoleId,
        roleIds: this.roleIds })
      this.$message.success('分配角色成功')
      this.close()
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}

</style>
